﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.ServiceProcess;
using System.Text;
using Aliyun.Api;
using Aliyun.Api.DNS.DNS20150109.Request;
using System.Timers;


namespace aDDNS
{
    public partial class ServiceMain : ServiceBase
    {
        LogConfig logconfig = new LogConfig();
        System.Timers.Timer IntervalSec = new System.Timers.Timer();

        public ServiceMain()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            
            logconfig.publicIP = "0.0.0.0";
            logconfig.acckeyID = "AAAAAA";
            logconfig.acckeySecret = "AAAAAAAA";
            logconfig.domainName = "exammple.com";
            logconfig.subDomainName = "www";
            logconfig.intervalSec = "10";
            logconfig.ReadConfig();
            IntervalSec.Interval = Convert.ToDouble(logconfig.intervalSec)*1000;
            IntervalSec.Elapsed += new ElapsedEventHandler(GetPublicIP);
            IntervalSec.Start();
        }

        protected override void OnStop()
        {
            IntervalSec.Stop();
        }

        public void GetPublicIP(object source, ElapsedEventArgs e)
        {
            string publicIP = null;
            try
            {
                string strUrl = "http://whatismyip.akamai.com/";
                Uri uri = new Uri(strUrl);
                WebRequest webreq = WebRequest.Create(uri);
                Stream s = webreq.GetResponse().GetResponseStream();
                StreamReader sr = new StreamReader(s, Encoding.Default);
                string all = sr.ReadToEnd();
                publicIP = all;
                if (publicIP != logconfig.publicIP)
                {
                    logconfig.WriteLog("IP变化  " + publicIP);
                    logconfig.publicIP = publicIP;
                    logconfig.SaveConfig();
                    SetDnsIP();
                }
            }
            catch (Exception)
            {
                publicIP = "0.0.0.0";
            }
            
        }

        public void SetDnsIP()
        {
            try
            {
                var aliyunClient = new DefaultAliyunClient("http://dns.aliyuncs.com/", logconfig.acckeyID, logconfig.acckeySecret);
                var req = new DescribeDomainRecordsRequest() { DomainName = logconfig.domainName };
                var response = aliyunClient.Execute(req);

                var updateRecord = response.DomainRecords.FirstOrDefault(rec => rec.RR == logconfig.subDomainName && rec.Type == "A");
                if (updateRecord == null)
                    return;
                logconfig.WriteLog("DNS记录值 " + updateRecord.Value);
                if (updateRecord.Value != logconfig.publicIP)
                {
                    var changeValueRequest = new UpdateDomainRecordRequest()
                    {
                        RecordId = updateRecord.RecordId,
                        Value = logconfig.publicIP,
                        Type = "A",
                        RR = logconfig.subDomainName
                    };
                    aliyunClient.Execute(changeValueRequest);
                    logconfig.WriteLog("更新DNS记录成功");
                }
            }
            catch (Exception ex)
            {
                logconfig.WriteLog("更新DNS记录错误  " + ex.ToString());
            }


        }
    }
}
